package com.Jian.reggie.controller;

import com.Jian.reggie.common.R;
import com.Jian.reggie.impl.User;
import com.Jian.reggie.service.UserService;
import com.Jian.reggie.utils.SMSUtils;
import com.Jian.reggie.utils.ValidateCodeUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * ClassName: UserController
 * Package: com.Jian.reggie.controller
 * Description:
 *
 * @Author 蹇泽阳
 * @Create 2023/11/28 17:06
 * @Version 1.0
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
  @Autowired
  private UserService userService;
  
  /**
   * 登录
   */
  @PostMapping("login")
  public R<String> login(@RequestBody User user, HttpServletRequest request, HttpSession session) {
    LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
    // 如果能查到手机，就登陆
    wrapper.eq(User::getPhone, user.getPhone());
    log.info(session.getAttribute(user.getPhone()).toString());
    log.info(user.getCode());
    if (!Objects.equals(session.getAttribute(user.getPhone()).toString(), user.getCode())) {
      return R.error("验证码不正确");
    }
    
    User oneUser = userService.getOne(wrapper);
    if (oneUser == null) {
      return R.error("手机号不正确，请联系蹇泽阳");
    }
    if (oneUser.getStatus() == 0) {
      return R.error("账号已被禁用，请联系蹇泽阳");
    }
    
    
    request.getSession().setAttribute("user", oneUser.getId());
    
    return R.success("登陆成功");
  }
  
  /**
   * 发送手机短信验证码
   */
  @PostMapping("/sendMsg")
  public R<String> sendMsg(@RequestBody String phone, HttpSession session) {
    
    // 获取手机号
    if (!StringUtils.isEmpty(phone)) {
      // 生成四位验证码
      String code = ValidateCodeUtils.generateValidateCode(4).toString();
      // 调用阿里云API发送短信，第一个参数：签名
      // 第二个参数：模版code
      // SMSUtils.sendMessage("小蹇的个人网站", "SMS_464075850", phone, code);
      // 生成的验证码保存到Session
      session.setAttribute(phone, code);
      // log.info(code);
      
      return R.success(code);
    }
    return R.error("手机验证码发送失败");
  }
  
  /**
   * 员工退出
   *
   * @param request
   * @return
   */
  @PostMapping("/loginout")
  public R<String> logout(HttpServletRequest request) {
    // 清理 Session中保存的当前登录员工的id
    request.getSession().removeAttribute("user");
    return R.success("退出成功");
  }
}
